package com.ts.zuul.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.UUID;


/**
 * Created by Zhou_Bing on 2018/9/6.
 */
@Component
public class ErrorFilter extends ZuulFilter{

    private static final Logger logger =LoggerFactory.getLogger(ErrorFilter.class);

    @Override
    public String filterType() {
        return "error";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {

        RequestContext ctx = RequestContext.getCurrentContext();
        Throwable throwable = ctx.getThrowable();
        if(ctx.getResponseStatusCode()==429){
            ctx.setResponseBody("{\"result\":\"Too Many Requests!\"}");
        }else{
            logger.error("this is a ErrorFilter :" + throwable.getCause().getMessage(), throwable);
            ctx.set("error.status_code", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            ctx.set("error.exception", throwable.getCause());
        }
        return null;
    }
}
